<?php
declare (strict_types=1);

namespace app\common\model;

use think\exception\ValidateException;
use think\Model;

/**
 * @mixin \think\Model
 */
class Base extends Model
{
    /**
     * 删除标识
     */
    const STATUS_F_1 = -1;
    /**
     * 正常
     */
    const STATUS_0 = 0;
    /**
     * 禁用
     */
    const STATUS_1 = 1;

    /**
     * getStatusNameAttr #
     *
     * @param $value
     * @param $data
     * @auth kouweihong
     * @date 2020/11/24
     * @return string
     */
    public function getStatusNameAttr($value, $data)
    {
        return $data['status'] == 0 ? '正常' : '禁用';
    }

    /**
     * getInfoByWhere #
     *
     * @param $where
     * @auth kouweihong
     * @date 2020/11/24
     * @return array|\think\db\concern\Model
     */
    public static function getInfoByWhere($where)
    {
        return static::where($where)->findOrEmpty();
    }

    /**
     * createRecord #
     *
     * @param $params
     * @param array $extend
     * @auth kouweihong
     * @date 2020/12/2
     * @return Base|Model
     */
    public static function createRecord($params, array $extend = [])
    {
        try {
            $static = static::create($params);
            if (!$static || !$static->{$static->getPk()}) throw new ValidateException('操作失败');

            return $static;
        } catch (ValidateException $e) {
            throw $e;
        }
    }

    /**
     * updateRecord #
     *
     * @param $params
     * @param null $where
     * @param array $extend
     * @auth kouweihong
     * @date 2020/12/2
     */
    public static function updateRecord($params, $where = null, array $extend = [])
    {
        try {
            $pk = (new static())->getPk();
            $where || (isset($params[$pk]) && ($where[$pk] = $params[$pk]));
            if (!$where) throw new ValidateException('更新条件为空');

            //更新数据
            $static = static::update($params, $where);
            if (!$static || !$static->{$pk}) throw new ValidateException('操作失败');

            return $static;
        } catch (ValidateException $e) {
            throw $e;
        }
    }
}
